import bleach
import markdown
from flask import render_template, Blueprint, request, redirect , url_for
from datetime import datetime
bp = Blueprint('blog',__name__ , url_prefix= '/blog' )
from exts import blogDB
from tools.editor.slug import create_slug
# write
@bp.route('/editor')
def write():
    return render_template('blog/editor.html')

@bp.route('/editor/post', methods=['POST'])
def create_post():
    # 处理表单数据
    title = request.form['title']
    raw_content = request.form['content']
    tags = [t.strip() for t in request.form.get('tags', '').split(',') if t.strip()]

    # Markdown 处理
    html_content = markdown.markdown(raw_content)
    from exts import ALLOWED_TAGS
    from exts import ALLOWED_ATTRIBUTES
    safe_html = bleach.clean(html_content, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES)

    # 创建文档
    post = {
        'title': title,
        'raw_content': raw_content,
        'html_content': safe_html,
        'author': '当前用户',  # 需替换为实际用户系统
        'created_at': datetime.now(),
        'tags': tags,
        'views': 0
    }

    # 存入数据库

    result = blogDB.insert_one(post)
    post_id = result.inserted_id

    post['slug'] = create_slug()
    # 更新数据库中的文章记录，添加 slug 字段
    blogDB.update_one({'_id': post_id}, {'$set': {'slug': post['slug']}})

    return redirect( url_for('blog.show_post', slug=post['slug']))


@bp.route('/editor/post/<slug>')
def show_post(slug):
    post = blogDB.find_one({'slug': slug})
    if not post:
        return "文章不存在", 404

    # 更新阅读量
    blogDB.update_one(
        {'_id': post['_id']},
        {'$inc': {'views': 1}}
    )

    return render_template('post.html', post=post)


# 博客页面
@bp.route('/<int:id>')
def post(id):
    # 验证 id 是否合法，这里简单检查 id 是否大于 0
    if id > 0:
        # 构建模板文件名，假设模板文件命名规则为 id.html
        template_name = f'blog/{id}.html'
        try:
            # 尝试渲染模板
            return render_template(template_name, id=id)
        except Exception as e:
            # 若模板文件不存在或其他渲染错误，返回错误信息
            return f"Error rendering template: {str(e)}", 404
    else:
        # 若 id 不合法，返回错误信息
        return "Invalid ID", 400